<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%" :close-on-click-modal="false"> 
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="140px" v-loading="formLoading">
      
      <el-row :gutter="20">
        <el-tag type="info" style="width: 100%;height: 30px;margin-bottom: 20px;">
        <h3>企业基本信息</h3>
      </el-tag>
        <el-col :span="8" v-if="formData.recordCode">
          <el-form-item label="档案编码" prop="recordCode">
            <span>{{ formData.recordCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="企业名称" prop="companyName">
            <el-input v-model="formData.companyName" placeholder="请输入企业名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
            <el-input v-model="formData.unifiedSocialCreditCode" placeholder="请输入统一社会信用代码" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="注册资金" prop="registeredCapital">
            <el-input v-model="formData.registeredCapital" placeholder="请输入注册资金" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="公司类型" prop="companyType">
            <el-input v-model="formData.companyType" placeholder="请输入公司类型" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="注册地址" prop="registeredAddress">
            <el-input v-model="formData.registeredAddress" placeholder="请输入注册地址" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="成立日期" prop="establishmentDate">
            <el-date-picker
v-model="formData.establishmentDate" type="date" value-format="YYYY-MM-DD"
              placeholder="选择成立日期" class="!w-full" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="经营期限" prop="operationPeriod">
            <el-input v-model="formData.operationPeriod" placeholder="请输入经营期限" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="介绍人" prop="referrer">
            <el-input v-model="formData.referrer" placeholder="请输入介绍人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="招商负责人" prop="investmentManager">
            <el-input v-model="formData.investmentManager" placeholder="请输入招商负责人" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="经营范围">
            <el-input v-model="formData.businessScope" type="textarea" :rows="5" placeholder="请输入经营范围" />
          </el-form-item>
        </el-col>
        <el-tag type="info" style="width: 100%;height: 30px;margin-bottom: 20px;">
        <h3>企业人员及账户信息</h3>
      </el-tag>
      <el-col :span="8">
          <el-form-item label="法定代表人" prop="legalPersonName">
            <el-input v-model="formData.legalPersonName" placeholder="请输入法定代表人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="法人身份证号" prop="legalPersonId">
            <el-input v-model="formData.legalPersonId" placeholder="请输入法人身份证号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="法人电话号码" prop="legalPersonPhone">
            <el-input v-model="formData.legalPersonPhone" placeholder="请输入法人电话号码" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="企业联系人" prop="companyContact">
            <el-input v-model="formData.companyContact" placeholder="请输入企业联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="企业联系电话" prop="contactPhone">
            <el-input v-model="formData.contactPhone" placeholder="请输入企业联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="企业邮箱" prop="companyEmail">
            <el-input v-model="formData.companyEmail" placeholder="请输入企业邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开户银行" prop="bankName">
            <el-input v-model="formData.bankName" placeholder="请输入开户银行" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开户账号" prop="bankAccount">
            <el-input v-model="formData.bankAccount" placeholder="请输入开户账号" />
          </el-form-item>
        </el-col>
        <el-tag type="info" style="width: 100%;height: 30px;margin-bottom: 20px;">
        <h3>企业相关属性信息</h3>
      </el-tag>
      <el-col :span="8">
          <el-form-item label="企业属性">
            <el-checkbox
:model-value="formData.simplified === 1"
                         @update:model-value="(val) => formData.simplified = val ? 1 : 0">简化企业</el-checkbox>
            <el-checkbox
:model-value="formData.keyEnterprise === 1"
                         @update:model-value="(val) => formData.keyEnterprise = val ? 1 : 0">重点企业</el-checkbox>
          </el-form-item>
        </el-col>
      <el-col :span="8">
          <el-form-item label="纳税人属性" prop="taxpayerType">
            <el-select v-model="formData.taxpayerType" placeholder="请选择纳税人属性" class="!w-full">
              <el-option
v-for="dict in getStrDictOptions(DICT_TYPE.OA_TAXPAYER_ATTRIBUTE)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="企业信用等级" prop="creditRating">
            <el-input v-model="formData.creditRating" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="委托内容" prop="entrustContent">
            <el-checkbox v-model="invoiceServiceChecked" @change="updateEntrustContent">开票</el-checkbox>
            <el-checkbox v-model="socialSecurityChecked" @change="updateEntrustContent">社保</el-checkbox>
            <el-checkbox v-model="housingFundChecked" @change="updateEntrustContent">公积金</el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="记账费开票">
            <el-checkbox
:model-value="formData.includeAccounting === 1"
              @update:model-value="(val) => formData.includeAccounting = val ? 1 : 0">{{ formData.includeAccounting === 1
                ? '是' : '否'}}</el-checkbox>
          </el-form-item>
        </el-col>
        <el-tag type="info" style="width: 100%;height: 30px;margin-bottom: 20px;">
        <h3>企业税务信息</h3>
      </el-tag>
        <el-col :span="8">
          <el-form-item label="所属经济城" prop="economicZone">
            <el-input v-model="formData.economicZone" placeholder="请输入所属经济城" />
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="登记机关" prop="registrationAuthority">
            <el-input v-model="formData.registrationAuthority" placeholder="请输入登记机关" />
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="主管税务机关" prop="taxOffice">
            <el-input v-model="formData.taxOffice" placeholder="请输入税务机关" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="税务管理员" prop="taxSupervisor">
            <el-input v-model="formData.taxSupervisor" placeholder="请输入税务管理员" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="委托开始时间" prop="entrustStartDate">
            <el-date-picker
v-model="formData.entrustStartDate" type="month" value-format="YYYY-MM"
              placeholder="选择委托开始时间" class="!w-full" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="委托结束时间" prop="entrustEndDate">
            <el-date-picker
v-model="formData.entrustEndDate" type="month" value-format="YYYY-MM"
              placeholder="选择委托结束时间" class="!w-full" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
              <el-form-item label="财务记账负责人" prop="accountingManager">
                <el-input v-model="formData.accountingManager" placeholder="请输入记账负责人" />
              </el-form-item>
            </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="网厅财务负责人" prop="onlineFinanceManager">
            <el-input v-model="formData.onlineFinanceManager" placeholder="请输入网厅财务负责人" />
          </el-form-item>
        </el-col> -->
        <!--        <el-col :span="24">-->
        <!--          <el-form-item label="委托内容">-->
        <!--            <el-checkbox v-model.number="formData.invoiceService">开票</el-checkbox>-->
        <!--            <el-checkbox v-model.number="formData.socialSecurity">社保</el-checkbox>-->
        <!--            <el-checkbox v-model.number="formData.housingFund">公积金</el-checkbox>-->
        <!--            <el-checkbox v-model.number="formData.simplified">是否为简化企业</el-checkbox>-->
        <!--            <el-checkbox v-model.number="formData.keyEnterprise">是否为重点企业</el-checkbox>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
<!--        <el-col :span="8">-->
<!--          <el-form-item label="企业信用等级" prop="creditRating">-->
<!--            <el-input v-model="formData.creditRating" placeholder="" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="8">-->
<!--          <el-form-item label="">-->
<!--            <el-checkbox :model-value="formData.simplified === 1"-->
<!--              @update:model-value="(val) => formData.simplified = val ? 1 : 0">简化企业</el-checkbox>-->

<!--            <el-checkbox :model-value="formData.keyEnterprise === 1"-->
<!--              @update:model-value="(val) => formData.keyEnterprise = val ? 1 : 0">重点企业</el-checkbox>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="5">
          <el-form-item label="收费价格(月)" prop="monthlyFee">
            <el-input v-model="formData.monthlyFee" placeholder="请输入金额" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="收款公司" prop="paymentCompany">
            <el-input v-model="formData.paymentCompany" placeholder="" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="5">
          <el-form-item label="开票备注" prop="invoiceRemark">
            <el-input v-model="formData.invoiceRemark" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="企业信用等级" prop="creditRating">
            <el-input v-model="formData.creditRating" placeholder="" />
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formData.remarks" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { AccountingCompaniesApi, AccountingCompaniesVO } from '@/api/oa/accountingcompanies'

/** 记账企业信息 表单 */
defineOptions({ name: 'AccountingCompaniesForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<Partial<AccountingCompaniesVO>>({
  id: undefined,
  economicZone: undefined,
  taxOffice: undefined,
  registeredCapital: undefined,
  operationPeriod: undefined,
  bankAccount: undefined,
  legalPersonName: undefined,
  legalPersonPhone: undefined,
  companyContact: undefined,
  contactPhone: undefined,
  investmentManager: undefined,
  companyName: undefined,
  taxpayerType: undefined,
  taxSupervisor: undefined,
  registeredAddress: undefined,
  companyEmail: undefined,
  supervisor: undefined,
  entrustStartDate: undefined,
  accountingManager: undefined,
  unifiedSocialCreditCode: undefined,
  registrationAuthority: undefined,
  companyType: undefined,
  establishmentDate: undefined,
  bankName: undefined,
  legalPersonId: undefined,
  entrustEndDate: undefined,
  onlineFinanceManager: undefined,
  businessScope: undefined,
  remarks: undefined,
  entrustContent: undefined,
  simplified: 0,
  keyEnterprise: 0,
  monthlyFee: undefined,
  includeAccounting: 0,
  invoiceRemark: undefined,
  paymentCompany: undefined,
  creditRating: undefined,
  creatorName: undefined,
  updaterName: undefined,
  referrer: undefined,
  entrustStartYear: undefined,
  entrustStartMonth: undefined,
  entrustEndYear: undefined,
  entrustEndMonth: undefined,
})

// 委托内容复选框状态
const invoiceServiceChecked = ref(false)
const socialSecurityChecked = ref(false)
const housingFundChecked = ref(false)

// 更新委托内容的方法
const updateEntrustContent = () => {
  const services: string[] = []
  if (invoiceServiceChecked.value) services.push('开票')
  if (socialSecurityChecked.value) services.push('社保')
  if (housingFundChecked.value) services.push('公积金')
  formData.value.entrustContent = services.join(',') || undefined
}

// 根据委托内容设置复选框状态
const setCheckboxStatus = () => {
  if (!formData.value.entrustContent) {
    invoiceServiceChecked.value = false
    socialSecurityChecked.value = false
    housingFundChecked.value = false
    return
  }

  const services = formData.value.entrustContent.split(',')
  invoiceServiceChecked.value = services.includes('开票')
  socialSecurityChecked.value = services.includes('社保')
  housingFundChecked.value = services.includes('公积金')
}
const formRules = reactive({
  companyName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
  economicZone: [{ required: true, message: '所属经济城不能为空', trigger: 'blur' }],
  taxOffice: [{ pattern: /^[\s\S]*$/, message: '税务所格式不正确', trigger: 'blur' }],
  registeredCapital: [{ required: true, pattern: /^[\s\S]*$/, message: '注册资金格式不正确', trigger: 'blur' }],
  operationPeriod: [{ pattern: /^[\s\S]*$/, message: '经营期限格式不正确', trigger: 'blur' }],
  // bankAccount: [
  //   { pattern: /^\d{16,19}$/, message: '开户账号格式不正确', trigger: 'blur' }
  // ],
  legalPersonName: [{ required: true, pattern: /^[\s\S]*$/, message: '法人姓名格式不正确', trigger: 'blur' }],
  legalPersonPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  companyContact: [{ pattern: /^[\s\S]*$/, message: '企业联系人格式不正确', trigger: 'blur' }],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  investmentManager: [{ pattern: /^[\s\S]*$/, message: '招商负责人格式不正确', trigger: 'blur' }],
  taxpayerType: [{ required: true, message: '纳税人属性不能为空', trigger: 'change' }],
  taxSupervisor: [{ pattern: /^[\s\S]*$/, message: '专管员格式不正确', trigger: 'blur' }],
  registeredAddress: [{ required: true, pattern: /^[\s\S]*$/, message: '注册地址格式不正确', trigger: 'blur' }],
  companyEmail: [
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' }
  ],
  supervisor: [{ pattern: /^[\s\S]*$/, message: '监事格式不正确', trigger: 'blur' }],
  entrustStartDate: [
    { required: false, message: '委托开始时间不能为空', trigger: 'change' },
    { pattern: /^\d{4}-\d{2}$/, message: '委托开始时间格式不正确，应为YYYY-MM格式', trigger: 'change' }
  ],
  entrustEndDate: [
    { required: false, message: '委托结束时间不能为空', trigger: 'change' },
    { pattern: /^\d{4}-\d{2}$/, message: '委托结束时间格式不正确，应为YYYY-MM格式', trigger: 'change' }
  ],
  monthlyFee: [
    { required: false, message: '收费价格(月)不能为空', trigger: 'blur' }
  ],
  accountingManager: [{ pattern: /^[\s\S]*$/, message: '记账负责人格式不正确', trigger: 'blur' }],
  unifiedSocialCreditCode: [
    { required: true, message: '统一社会信用代码不能为空', trigger: 'blur' },
    { pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/, message: '统一社会信用代码格式不正确', trigger: 'blur' }
  ],
  registrationAuthority: [{ required: true, message: '登记机关不能为空', trigger: 'blur' }],
  companyType: [{ required: true, message: '公司类型不能为空', trigger: 'blur' }],
  establishmentDate: [{ required: true, pattern: /^[\s\S]*$/, message: '成立日期格式不正确', trigger: 'change' }],
  bankName: [{ pattern: /^[\s\S]*$/, message: '开户银行格式不正确', trigger: 'blur' }],
  legalPersonId: [
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  onlineFinanceManager: [{ pattern: /^[\s\S]*$/, message: '网厅财务负责人格式不正确', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await AccountingCompaniesApi.getAccountingCompanies(id)
      
      // 将年份和月份字段组合成字符串格式用于前端显示
      if ((data as any).entrustStartYear && (data as any).entrustStartMonth) {
        const year = String((data as any).entrustStartYear).padStart(4, '0')
        const month = String((data as any).entrustStartMonth).padStart(2, '0')
        data.entrustStartDate = `${year}-${month}`
      }
      
      if ((data as any).entrustEndYear && (data as any).entrustEndMonth) {
        const year = String((data as any).entrustEndYear).padStart(4, '0')
        const month = String((data as any).entrustEndMonth).padStart(2, '0')
        data.entrustEndDate = `${year}-${month}`
      }
      
      formData.value = data
      // 设置复选框状态
      setCheckboxStatus()
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as AccountingCompaniesVO
    
    // 将字符串格式的委托时间转换为年份和月份字段
    if (data.entrustStartDate) {
      try {
        const startParts = data.entrustStartDate.split('-')
        if (startParts.length === 2) {
          const year = Number(startParts[0])
          const month = Number(startParts[1])
          if (!isNaN(year) && !isNaN(month) && year > 0 && month >= 1 && month <= 12) {
            data.entrustStartYear = year || 0
            data.entrustStartMonth = month || 0
          }
        }
      } catch (error) {
        console.error('解析委托开始时间失败:', error)
      }
    }
    
    if (data.entrustEndDate) {
      try {
        const endParts = data.entrustEndDate.split('-')
        if (endParts.length === 2) {
          const year = Number(endParts[0])
          const month = Number(endParts[1])
          if (!isNaN(year) && !isNaN(month) && year > 0 && month >= 1 && month <= 12) {
            data.entrustEndYear = year || 0
            data.entrustEndMonth = month || 0
          }
        }
      } catch (error) {
        console.error('解析委托结束时间失败:', error)
      }
    }
    
    if (formType.value === 'create') {
      await AccountingCompaniesApi.createAccountingCompanies(data)
      message.success(t('common.createSuccess'))
    } else {
      await AccountingCompaniesApi.updateAccountingCompanies(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    economicZone: undefined,
    taxOffice: undefined,
    registeredCapital: undefined,
    operationPeriod: undefined,
    bankAccount: undefined,
    legalPersonName: undefined,
    legalPersonPhone: undefined,
    companyContact: undefined,
    contactPhone: undefined,
    investmentManager: undefined,
    companyName: undefined,
    taxpayerType: undefined,
    taxSupervisor: undefined,
    registeredAddress: undefined,
    companyEmail: undefined,
    supervisor: undefined,
    entrustStartDate: undefined,
    accountingManager: undefined,
    unifiedSocialCreditCode: undefined,
    registrationAuthority: undefined,
    companyType: undefined,
    establishmentDate: undefined,
    bankName: undefined,
    legalPersonId: undefined,
    entrustEndDate: undefined,
    onlineFinanceManager: undefined,
    businessScope: undefined,
    remarks: undefined,
    entrustContent: undefined,
    simplified: 0,
    keyEnterprise: 0,
    monthlyFee: undefined,
    includeAccounting: 0,
    invoiceRemark: undefined,
    paymentCompany: undefined,
    creditRating: undefined,
    creatorName: undefined,
    updaterName: undefined,
  }
  // 重置复选框状态
  invoiceServiceChecked.value = false
  socialSecurityChecked.value = false
  housingFundChecked.value = false
  formRef.value?.resetFields()
}
</script>
